package a07_二叉树;

/**
 * <p>
 * a30_删除二叉搜索树中的节点复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/4/23
 */
public class a30_删除二叉搜索树中的节点复习2 {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }

        if (key < root.val) {
            root.left = deleteNode(root.left, key);
        }else if (key > root.val) {
            root.right = deleteNode(root.right, key);
        }else {
            if(root.left == null && root.right == null){
                return null;
            }else if(root.left != null && root.right == null){
                return root.left;
            }else if(root.left != null && root.right == null){
                return root.right;
            }else {
                TreeNode mostLeftNode = root.right;
                while (mostLeftNode.left != null){
                    mostLeftNode = mostLeftNode.left;
                }

                mostLeftNode.left = root.left;
                return root.right;
            }
        }
        return root;
    }
}
